package cn.chiship.bs.api.core.config;

import cn.chiship.sdk.core.enums.BaseResultEnum;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.*;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpMethod;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.*;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/***
 * @author: lijian
 */
@Configuration
@EnableOpenApi
public class Swagger3Config extends WebMvcConfigurationSupport {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(responseBodyConverter());
        super.configureMessageConverters(converters);
    }

    @Bean
    public HttpMessageConverter responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        return converter;
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .groupName("默认分组")
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .globalResponses(HttpMethod.GET, globalResponseMessage())
                .globalResponses(HttpMethod.POST, globalResponseMessage())
                .globalRequestParameters(generateRequestParameters());
    }

    /**
     * 配置基本信息
     *
     * @return
     */
    @Bean
    public ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("JAVA接口模版系统")
                .description("JAVA接口模版系统")
                .version("1.0.0")
                .contact(new Contact("李剑", "https://gitee.com/chiship", "li1991-hello@163.com"))
                .build();

    }

    /**
     * 增加如下配置可解决Spring Boot  与Swagger 3.0.0 不兼容问题
     **/
    @Bean
    public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
    }

    private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
        return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
    }

    public static List globalResponseMessage() {
        List<Response> globalResponses = new ArrayList<>();
        for (BaseResultEnum item : BaseResultEnum.values()) {
            globalResponses.add(new ResponseBuilder()
                    .code(String.valueOf(item.getCode()))
                    .description(item.getMessage())
                    .build());
        }
        return globalResponses;
    }
    private List<RequestParameter> generateRequestParameters() {
        List<RequestParameter> parameters = new ArrayList();
        parameters.add(new RequestParameterBuilder()
                .name("ProjectsId")
                .description("ProjectsId")
                .in(In.HEADER.toValue())
                .required(true)
                .query(
                        builder -> builder.defaultValue("1883442361")
                                .model(m -> m.scalarModel(ScalarType.STRING)))
                .build());
        parameters.add(new RequestParameterBuilder()
                .name("App-Id")
                .description("appId")
                .in(In.HEADER.toValue())
                .required(true)
                .query(
                        builder -> builder.defaultValue("602394140839161856")
                                .model(m -> m.scalarModel(ScalarType.STRING)))
                .build());
        parameters.add(new RequestParameterBuilder()
                .name("App-Key")
                .description("appKey")
                .in(In.HEADER.toValue())
                .required(true)
                .query(
                        builder -> builder.defaultValue("e027565ee9954929a41c152deecdf1c1")
                                .model(m -> m.scalarModel(ScalarType.STRING)))
                .build());
        parameters.add(new RequestParameterBuilder()
                .name("Sign")
                .description("参数签名(RSA私钥签名或MD5参数加密)")
                .in(In.HEADER.toValue())
                .required(false)
                .query(
                        builder -> builder.defaultValue("MD5=")
                                .model(m -> m.scalarModel(ScalarType.STRING)))
                .build());
        parameters.add(new RequestParameterBuilder()
                .name("Access-Token")
                .description("登录令牌")
                .in(In.HEADER.toValue())
                .required(false)
                .query(
                        builder -> builder.defaultValue("1883442361")
                                .model(m -> m.scalarModel(ScalarType.STRING)))
                .build());
        return parameters;
    }
}